package com.schoolvisitors.service;

import com.schoolvisitors.entity.Floor;
import com.schoolvisitors.exception.BusinessException;
import com.schoolvisitors.repository.FloorRepository;
import com.schoolvisitors.repository.RoomRepository;
import com.schoolvisitors.response.ResultCode;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class FloorService {
    private final FloorRepository floorRepository;
    private final RoomRepository roomRepository;

    @Autowired
    public FloorService(FloorRepository floorRepository, RoomRepository roomRepository){
        this.floorRepository = floorRepository;
        this.roomRepository = roomRepository;
    }

    // 缓存floorId
    private final Map<Long, Floor> floorCache = new ConcurrentHashMap<>();

    // 服务初始化后加载所有floor缓存
    @PostConstruct
    public void initCache() {
        List<Floor> floors = floorRepository.findAllByDeleteFalse();
        floorCache.clear();
        for (Floor floor : floors) {
            floorCache.put(floor.getId(), floor);
        }
    }

    public Floor createFloor(Floor floor) {
        if (floorRepository.existsByName(floor.getName())) {
            throw new BusinessException(ResultCode.FLOOR_NAME_IS_USE);
        }
        if (floorRepository.existsByNumber(floor.getNumber())) {
            throw new BusinessException(ResultCode.FLOOR_NUMBER_IS_USE);
        }
        Floor saved = floorRepository.save(floor);
        floorCache.put(saved.getId(), saved);
        return saved;
    }

    public void deleteFloor(Long floorId) {
        Optional<Floor> floor = floorRepository.findByIdAndDeleteFalse(floorId);
        if (floor.isPresent()) {
            // 查询是否有房间属于该楼层
            boolean hasRooms = roomRepository.existsByFloorIdAndDeleteFalse(floorId);
            if (hasRooms) {
                // 如果有房间，抛出异常
                throw new BusinessException(ResultCode.FLOOR_HAS_ROOMS);
            }
            // 没有房间，才能删除
            Floor saved = floor.get();
            saved.setDelete(true);
            floorRepository.save(saved);
            floorCache.remove(floorId);
        } else {
            throw new BusinessException(ResultCode.FLOOR_ID_NOT_FOUND);
        }
    }

    public List<Floor> getFloors() {
        return new ArrayList<>(floorCache.values());
    }

    public Floor getFloorById(Long floorId) {
        Floor floor = floorCache.get(floorId);
        if (floor == null) {
            throw new BusinessException(ResultCode.FLOOR_ID_NOT_FOUND);
        }
        return floor;
    }

}
